import React, { useState, useCallback } from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    RefreshControl,
} from 'react-native';
import Loading from '../../components/items/Loading';
import Home from '../../pages/Home';

const wait = (timeout: number) => new Promise<void>(res => setTimeout(res, timeout));

const App = () => {
    // 控制初始加载状态
    const [isInitialLoading, setIsInitialLoading] = useState(true);

    // 控制下拉刷新状态
    const [refreshing, setRefreshing] = useState(false);

    // 模拟初始加载过程
    React.useEffect(() => {
        const loadInitialData = async () => {
            try {
                await wait(2000);
                setIsInitialLoading(false);
            } catch (error) {
                console.error('初始加载失败:', error);
            }
        };

        loadInitialData();
    }, []);

    // 下拉刷新处理函数
    const onRefresh = useCallback(async () => {
        setRefreshing(true);
        try {
            await wait(1500);
            // 刷新完成后，可以更新数据状态
        } catch (error) {
            console.error('刷新失败:', error);
        } finally {
            setRefreshing(false);
        }
    }, []);

    // 初始加载时显示全屏加载页
    if (isInitialLoading) {
        return (
            <SafeAreaView style={styles.fullScreenContainer}>
                <Loading
                    message="启动中..."
                    isFullScreen={false}
                    backgroundColor="#FFFFFF"
                />
            </SafeAreaView>
        );
    }

    // 初始加载完成后显示主界面
    return (
        <SafeAreaView style={styles.container}>
            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        onRefresh={onRefresh}
                        colors={['#007AFF']}
                        tintColor="#007AFF"
                    />
                }
            >
                {/* 直接渲染Home组件 */}
                <Home />
            </ScrollView>
            {/* 移除下拉刷新时的全屏Loading组件 */}
            {/* {refreshing && (
                <Loading
                    isFullScreen={true}
                    message="刷新中..."
                    backgroundColor="rgba(255, 255, 255, 0.8)"
                />
            )} */}
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({
    fullScreenContainer: {
        flex: 1,
        backgroundColor: '#FFFFFF',
    },
    container: {
        flex: 1,
        backgroundColor: '#FFFFFF',
    },
});

export default App;